package service

import (
	"database/sql"
	"errors"
	"gadmin/model"
)

func CreateDatasource(datasource model.Datasource) (err error) {
	result := model.DB.Create(&datasource)
	return result.Error
}

func GetDatasource() (datasources []model.Datasource, err error) {
	result := model.DB.Find(&datasources)
	if result.Error != nil {
		return nil, result.Error
	}
	return datasources, nil
}

func DeleteDatasource(id int64) (err error) {
	result := model.DB.Delete(&model.Datasource{}, id)
	if result.Error != nil {
		return result.Error
	}
	return nil
}

func PreviewDatasource(id int64) (data []interface{}, err error) {
	var datasource model.Datasource
	result := model.DB.Where("id = ?", id).Find(&datasource)
	if result.Error != nil {
		return nil, result.Error
	}
	if datasource.Type == "mysql" {
		db, err := sql.Open("mysql", datasource.MySQLDSN)
		if err != nil {
			return nil, err
		}
		defer db.Close()

		rows, err := db.Query(datasource.SQL)
		if err != nil {
			return nil, err
		}
		defer rows.Close()

		data = make([]interface{}, 0)
		cols, err := rows.Columns()
		if err != nil {
			return nil, err
		}

		// colTypes, err := rows.ColumnTypes()
		// if err != nil {
		// 	return nil, err
		// }

		for rows.Next() {
			columns := make([]interface{}, len(cols))
			columnPointers := make([]interface{}, len(cols))
			for i, _ := range columns {
				// fmt.Println(colTypes[i].ScanType().Name())
				// columns[i] = reflect.New(colTypes[i].ScanType())
				columnPointers[i] = &columns[i]
			}

			if err := rows.Scan(columnPointers...); err != nil {
				return nil, err
			}

			row := make(map[string]interface{})
			for i, colName := range cols {
				switch columns[i].(type) {
				case []byte:
					row[colName] = string(columns[i].([]byte))
				default:
					row[colName] = columns[i]
				}
			}
			data = append(data, row)
		}
		return data, nil
	}
	return nil, errors.New("不支持的数据源类型")
}
